local QuickChat = MClass("QuickChat")

--ctor 初始化UI init设置静态数据 setData设置动态数据
function QuickChat:ctor()
    --self.root 默认为根节点
    self.msgs = {}

    local function touchEvent_Chat(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local index = sender:getTag()
            local content = self.msgs[index].content
            BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.PLAYER_TALK,content)
            self:setVisible(false)
        end
    end
    self.panel = self:findChild("Panel")
   for i=1,Constant.BattleTalkCount do
   		local msg = {}
   		msg.txt = self:findChild("Panel/Text_"..i)
   		msg.btn = self:findChild("Panel/Button_"..i)
   		msg.btn:setTag(i)
   		msg.btn:addTouchEventListener(touchEvent_Chat)
   		self.msgs[i] = msg
   end
	self:init()
end

function QuickChat:init()
      self:setVisible(false)
      BattleUIEvent:addEventListener(BattleUIEvent.TYPE.QC_SHOW,handler(self,QuickChat.show))


    -- add touch for cancel
    local touchLayer = display.newLayer()
    local touchSize = self.panel:getContentSize()
    touchLayer:setContentSize(touchSize)
    touchLayer:setPosition(cc.p(-touchSize.width,-touchSize.height))
    touchLayer:setTouchEnabled(true)
    self.root:addChild(touchLayer)

     local function touchBegan(touch, event)
        local locationX,locationY = touch:getLocation2()
        local boundingBox = self.panel:getBoundingBox()
        local localPos = self.root:convertToNodeSpace(cc.p(locationX,locationY))
        if cc.rectContainsPoint(boundingBox,localPos) then
            return false
        else
            return true
        end
    end

    local function touchMoved(touch, event)
    end

    local function touchEnded(touch, event)
        local locationX,locationY = touch:getLocation2()
        local boundingBox = self.panel:getBoundingBox()
        local localPos = self.root:convertToNodeSpace(cc.p(locationX,locationY))
        if cc.rectContainsPoint(boundingBox,localPos) then
           --todo 
        else
            self:setVisible(false)
        end
    end

    local touchListener = cc.EventListenerTouchOneByOne:create()
    touchListener:registerScriptHandler(touchBegan,cc.Handler.EVENT_TOUCH_BEGAN)
    touchListener:registerScriptHandler(touchMoved,cc.Handler.EVENT_TOUCH_MOVED)
    touchListener:registerScriptHandler(touchEnded,cc.Handler.EVENT_TOUCH_ENDED)
    self:getEventDispatcher():addEventListenerWithSceneGraphPriority(touchListener, touchLayer)
end

function QuickChat:setData()
end

function QuickChat:updateData()
	local setting = UD.setting
	for i=1,Constant.BattleTalkCount do
		local msg = self.msgs[i]
		local content = UD.setting:getBattleTalkContent(i)
		msg.content = content
		if content then
			content = string.uomitstr(content,Constant.BattleTalkShowNum)
			msg.txt:setString(content)
		end
	end


end

function QuickChat:show()
	self:setVisible(true)
	self:updateData()
end

return QuickChat